#!/bin/sh
LOCAL=`mktemp -d`
echo '#!/bin/sh' > ${LOCAL}/atexit
chmod a+x ${LOCAL}/atexit
trap "${LOCAL}/atexit ; rm -rf $LOCAL" EXIT
trap "exit" INT QUIT TERM

#LOCAL=`pwd`
TMPJSONVAL=${LOCAL}/tmpval.json
TMPJSONOUT=${LOCAL}/tmpout.json

JSONFILE=$1
POS=$2
KEY=$3
VALUE=$4

#declare JSONFILE=$1
#declare POS=$2
#declare KEY=$3
#declare VALUE=$4
#echo $JSONFILE $POS $KEY $VALUE

if [ ! -f ${JSONFILE} ]; then
    echo '{}' > ${JSONFILE}
    echo "TEST_MAC_CUR:0002"
else
    echo `ifconfig|grep "1c:83:41"|awk '{print $5}'`
fi

if [ -z "$VALUE" ] ; then
    echo Usage: $0 JSONFILE POS KEY TMPJSONVAL >&2
    exit 1
fi
echo "$VALUE" > $TMPJSONVAL
if ! jq . "$TMPJSONVAL" > /dev/null 2>&1 ; then
    echo "'$TMPJSONVAL' not 1 in JSON format" >&2
    exit 1
fi
if ! jq . "$JSONFILE" > /dev/null 2>&1 ; then
    echo "$JSONFILE not 2 in JSON format" >&2
    exit 1
fi
#echo $JSONFILE

#B="\"bgg\""
#B="\"$VALUE\""
#if jq "$POS += {$KEY: "\"$VALUE\"" }" "$JSONFILE" > $TMPJSONOUT ; then
if jq "$POS += {$KEY: $VALUE }" "$JSONFILE" > $TMPJSONOUT ; then
    mv $TMPJSONOUT "$JSONFILE"
    exit 0
else
    exit 1
fi